import Editor from '../editor'
import { RenderView } from '../view'


export class KeyboardEvent {
  editor: Editor
  container: HTMLElement
  view
  // [x: string]: any
  constructor(editor: Editor, container: HTMLElement, view: RenderView) {
    this.editor = editor
    this.container = container
    this.view = view
  }
  /**
   * @description 对于输入事件的处理
   * @param e 当前的对象
   */
  beforeInputHandler_(e: {
    inputType: any
    preventDefault: () => void
    data: any
  }) {
    console.log('inputType', e)

    const inputType = e.inputType
    // 拦截默认事件 自己处理
    e.preventDefault()
    switch (inputType) {
      case 'insertText':
        const text = e.data
        if (text) {
          this.editor.insertTextAtCursor(text)
        }
        break
      case 'deleteContentBackward':
        this.editor.deleteTextAtCursor();
        break;
      case 'insertParagraph':
        this.editor.insertTextAtCursor('\n')
      default:
        break
    }
  }
  private selectionchangeHandler_(selection: { anchor: any; focus: any }) {
    if (selection) {
      this.editor.setSelection(selection.anchor, selection.focus)
    }
  }
  /**
   * @description 监听键盘输入事件
   */
  addListeners() {
    this.container.addEventListener(
      'beforeinput',
      this.beforeInputHandler_.bind(this)
    )
    this.view.on('selection-change', this.selectionchangeHandler_.bind(this))
  }
}
export default KeyboardEvent
